﻿/// <reference path="jquery-1.3.2-vsdoc.js"/>
/*

Coded by Nguyen Quang Huy
Y!M: nasavietnam, nasa8x
Email: nasavietnam@gmail.com
Website: www.nasa8x.com
www.vualaptrinh.com
www.nasavietnam.com
www.xomnet.org

*/



(function ($) {
    $.extend({
        MvcForum: {
            minutePageRefresh: 10,
            prefix: 'mvcforum_',
            ajaxContainer: '#_contentPanel',
            loadingId: '#_loading',
            cookieDays: 30,
            xFileManager: true,
            messages: {},
            Cookie: {

                add: function (name, value, days) {
                    var expires = '';
                    if (days) {
                        var date = new Date();
                        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                        expires = "; expires=" + date.toGMTString();
                    }
                    else

                        document.cookie = name + "=" + value + expires + "; path=/";
                },
                get: function (name) {
                    var nameEQ = name + "=";
                    var ca = document.cookie.split(';');
                    for (var i = 0; i < ca.length; i++) {
                        var c = ca[i];
                        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                        if (c.indexOf(nameEQ) == 0) {
                            return c.substring(nameEQ.length, c.length);
                        }
                    }
                    return "";
                },
                remove: function (name) {
                    this.Add(name, "", -1);
                }
            },

            String: {
                trim: function () {
                    return this.replace(/^\s+|\s+$/g, '');

                },

                //if( $.StringEx.isNullOrEmpty('') ) alert('Empty string');
                isNullOrEmpty: function (value) {
                    if (value) {
                        if (typeof (value) == 'string') {
                            if (value.length > 0)
                                return false;
                        }
                        if (value != null)
                            return false;
                    }
                    return true;

                },

                replace: function (source, oldVal, newVal) {
                    var result = source;
                    //result = result.replace(oldVal, newVal);
                    //result = result.replace(new RegExp(oldVal, 'ig'), newVal);
                    result = result.replace(new RegExp('\\' + oldVal + '\\', 'g'), newVal);

                    return result;
                },

                //alert( $.StringEx.format("Hello {0}.","MvcForum") );
                format: function (format, args) {
                    var result = format;
                    for (var i = 1; i < arguments.length; i++) {
                        result = result.replace(new RegExp('\\{' + (i - 1) + '\\}', 'g'), arguments[i]);
                    }
                    return result;
                },
                startsWith: function (prefix, ignoreCase) {
                    if (!prefix) return false;
                    if (prefix.length > this.length) return false;
                    if (ignoreCase) {
                        if (ignoreCase == true) {
                            return (this.substr(0, prefix.length).toUpperCase() == prefix.toUpperCase());
                        }
                    }
                    return (this.substr(0, prefix.length) === prefix);
                },
                endsWith: function (suffix, ignoreCase) {
                    if (!suffix) return false;
                    if (suffix.length > this.length) return false;
                    if (ignoreCase) {
                        if (ignoreCase == true) {
                            return (this.substr(this.length - suffix.length).toUpperCase() == suffix.toUpperCase());
                        }
                    }
                    return (this.substr(this.length - suffix.length) === suffix);
                }
            },


            Menu:
            {
                showId: null,
                triggerClass: '.dropdown-menu',
                showSpeed: 500,
                hideSpeed: 200,
                subTop: 1,
                subLeft: 0,
                init: function () {

                    $(this.triggerClass).mouseover(function () {
                        $.MvcForum.Menu.show(this, $(this).metadata().target);
                    });

                },
                show: function (_parent, _target) {

                    var _mainParent = _parent;
                    if (_target != null) {
                        //var _dimensions = { w: $(_parent).offset().width, h: $(_parent).offset().height, left: $(_parent).offset().left, top: $(_parent).offset().top };
                        var _dimensions = $(_parent).offset();
                        //alert("w:" + _dimensions.w + "h:" + _dimensions.h + "left:" + _dimensions.left + "top:" + _dimensions.top);

                        var winW = $(window).width();
                        var winH = $(window).height();
                        if (winW > _dimensions.left + $(_target).outerWidth()) {
                            $(_target).css('top', _dimensions.top + $(_parent).outerHeight() + this.subTop).css('left', _dimensions.left + this.subLeft);
                        }
                        else {
                            var _rightPos = winW - (_dimensions.left + $(_parent).outerWidth() + this.subLeft);
                            $(_target).css('top', _dimensions.top + $(_parent).outerHeight() + this.subTop).css('right', _rightPos);
                        }
                        $(_target).slideDown(this.showSpeed);

                    }

                    if (_target != this.showId) {
                        this.hide();
                    }
                    this.showId = _target;

                    // hide when mouse click

                    $(document).click(function (event) {

                        if ($.MvcForum.Menu.showId != null) {
                            if (this !== event.target && (/textarea|select/i.test(event.target.nodeName) || event.target.type === "text")) {
                                return;
                            }
                            else {
                                $.MvcForum.Menu.hide();
                            }
                        }
                        //alert(event.pageX + ' - ' + _dimensions.left + '- ' + (_dimensions.left + $(_target).outerWidth()));

                    });



                },
                hide: function () {

                    if (this.showId != null) {
                        $(this.showId).slideUp(this.hideSpeed);
                        this.showId = null;

                    }

                }

            },


            Tooltip: {
                isShowed: false,
                opacity: 0.9,
                offsetPointerX: 12,
                offsetPoinerY: 10,
                show: function (_htmlTitle) {
                    var _html = "<div id=\"tooltip_container\" class=\"tooltip-container\">" +
                               "<div class=\"tooltip-pointer\">" +

                               "</div>" +
                               "<div id=\"tooltip_content\">" +
                               "</div>" +
                               "</div>";

                    //$('body').a
                    $('#tooltip_container').css({ opacity: this.opacity });
                    $('#tooltip_content').html(_htmlTitle).css({ opacity: 1 });

                }
            },
            _undefined: function () {
                for (var i = 0; i < arguments.length; i++)
                    if (typeof arguments[i] != 'undefined') return false;
                return true;
            },


            _viewport: function () {
                var d = document.documentElement, b = document.body, w = window;
                return jQuery.extend(
                    jQuery.browser.msie ?
                        { left: b.scrollLeft || d.scrollLeft, top: b.scrollTop || d.scrollTop} :
                        { left: w.pageXOffset, top: w.pageYOffset },
                    !this._undefined(w.innerWidth) ?
                        { width: w.innerWidth, height: w.innerHeight} :
                        (!this._undefined(d) && !this._undefined(d.clientWidth) && d.clientWidth != 0 ?
                            { width: d.clientWidth, height: d.clientHeight} :
                            { width: b.clientWidth, height: b.clientHeight }));
            },

            _overlay: function (status, callback) {
                switch (status) {
                    case 'show':
                        $("body").append('<div ondblclick="$.MvcForum.hideLoading()" class="overlay" id="_overlay"></div>');
                        $("#_overlay").css({
                            opacity: 0.2,
                            height: $(document).height()

                        }).fadeIn(500, function () {


                            if ($.isFunction(callback))
                                callback.apply();
                        });
                        break;
                    case 'hide':
                        $('#_overlay').fadeOut('fast', function () {
                            $("#_overlay").remove();
                            if ($.isFunction(callback))
                                callback.apply();

                        });

                        break;
                }
            },

            appendPrefix: function (_name) {

                return this.prefix + _name;
            },

            Collapse: {

                init: function () {

                    var _colls = unescape($.MvcForum.Cookie.get($.MvcForum.appendPrefix('collapse')));
                    if (_colls.length > 0) {
                        var _collapse = _colls.split('|');
                        for (var i = 0; i < _collapse.length; i++) {
                            if (_collapse[i].length > 0) {
                                $(_collapse[i]).hide();

                                $('.collapse').each(function () {
                                    if ($(this).metadata().collapseId == _collapse[i]) {
                                        $(this).removeClass('collapse-close')
                                           .addClass('collapse-open');
                                    }
                                });

                            }

                        }

                    };


                    $('.collapse').click(
		                function () {

		                    if ($(this).hasClass('collapse-open')) {
		                        $(this).removeClass('collapse-open');
		                        $(this).addClass('collapse-close');
		                        $.MvcForum.Collapse.show($(this).metadata().collapseId);


		                    } else {
		                        $(this).removeClass('collapse-close');
		                        $(this).addClass('collapse-open');
		                        $.MvcForum.Collapse.hide($(this).metadata().collapseId);
		                    }


		                });

                },

                show: function (id) {
                    var _cookieName = $.MvcForum.appendPrefix('collapse');
                    var _colls = unescape($.MvcForum.Cookie.get(_cookieName));
                    _colls = _colls.replace("|" + id, "");
                    $.MvcForum.Cookie.add(_cookieName, escape(_colls), $.MvcForum.cookieDays);
                    $(id).slideDown('fast');
                },
                hide: function (id) {
                    var _cookieName = $.MvcForum.appendPrefix('collapse');
                    var _colls = unescape($.MvcForum.Cookie.get(_cookieName));
                    _colls += "|" + id;
                    $.MvcForum.Cookie.add(_cookieName, escape(_colls), $.MvcForum.cookieDays);
                    $(id).slideUp('fast');


                }

            },


            preLoadImages: function () {
                var args_len = arguments.length;
                for (var i = args_len; i--; ) {
                    var cacheImage = document.createElement('img');
                    cacheImage.src = arguments[i];
                    cache.push(cacheImage);
                }

            },



            showLoading: function (sender, args) {
                $.MvcForum._overlay('show');
                var _v = $.MvcForum._viewport();
                var _left = (_v.width - $($.MvcForum.loadingId).outerWidth()) / 2;
                var _top = _v.top + (_v.height - $($.MvcForum.loadingId).outerHeight()) / 2;
                $($.MvcForum.loadingId).css({ top: _top, left: _left }).show();

                //alert('Loading');

            },
            hideLoading: function (sender, args) {
                $($.MvcForum.loadingId).fadeOut();
                $.MvcForum._overlay('hide');
            },


            toggleCheckbox: function (_state, _forClass) {

                // default
                var _class = 'input.item-selected';

                if (_forClass) _class = _forClass;

                $(_class).each(function () {
                    $(this).attr("checked", _state);
                });

            },
            getSelectedItems: function (_forClass) {
                var _items = new Array();

                var _class = 'input.item-selected';

                if (_forClass) _class = _forClass;
                // $("input[@class='item-selected']:checked").each(function() {
                $(_class).each(function () {
                    if ($(this).attr("checked") == true) {
                        _items.push($(this).val());
                    }
                });
                return _items;

            },

            deleteConfirm: function (callback) {
                var _selectedItems = this.getSelectedItems();
                if (_selectedItems > 0) {
                    Confirm($.MvcForum.String.format($.MvcForum.messages.deleteItemsConfirm, _selectedItems), null, function (r) {
                        if (r) {
                            if ($.isFunction(callback)) {
                                callback.apply();
                            }
                        }


                    });
                }
                else {
                    Alert($.MvcForum.messages.mustSelectItem);
                };
            },

            resetElement: function () {

                // Set class for button
                /*
                $('input:button,input:submit,input:reset')
                .addClass('button')
                .mouseover(function () {
                $(this).addClass('button-over');
                })
                .mouseout(function () {
                $(this).removeClass('button-over');
                });

              

                $('input:checkbox')
                .click(function () {
                if ($(this).attr('checked')) {
                $(this).val('True');
                }
                else {

                $(this).val('False');

                }

                });

                */
                //var max = 0;
                //    $(".fr-field dt").each(function () {
                //        if ($(this).width() > max)
                //            max = $(this).width();
                //    });
                //    $(".fr-field dt").width(max);

                //    alert(max)


                // Disable Submit

                // $('form').attr('onsubmit', 'return false');

                //Set class for textbox input:file,
                /*
                $('input:text,input:password,textarea')
                .addClass('input').focus(function () {
                if (!$(this).hasClass('focus-no-addclass')) {
                $(this).addClass('input-focus');
                }
                })
                .blur(function () {
                $(this).removeClass('input-focus');
                });

                */

                // ComboBox reset contrains Jquery.dd

                //                if ($.fn.msDropDown)
                //                    $('select').msDropDown();
            },


            niceGrid: function () {
                // Set Gridview Style

                $('.gridview tr')
                        .hover(
                            function () {
                                $(this).addClass('row-hover');
                            },
                            function () {
                                $(this).removeClass('row-hover');
                            })


                        .click(function (e) {

                            if (!e.ctrlKey) {
                                $('.gridview tr.row-selected input.item-selected').attr('checked', false);
                                $('.gridview tr.row-selected').removeClass('row-selected');

                            };

                            $('.gridview tr.row-current').removeClass('row-current');
                            $(this).addClass('row-selected row-current');
                            $(this).find('input.item-selected').attr('checked', true);

                            $(this).noSelect();

                        });
            },

            forumJump: function (_target) {
                if (_target.length > 0) {

                    window.location = _target;

                }

            },

            htmlEditor: function () {

                if ($("textarea.tinymce").length <= 0) return;

                /*

                $('form').bind('form-pre-serialize', function (e) {
                tinyMCE.triggerSave();
                });

                */

                var _toolbar1 = '';
                var _toolbar2 = '';
                var _toolbar3 = '';
                var _toolbar4 = '';
                var _xfm = this.xFileManager ? '$.MvcForum.xfilemanagerCallback' : '';

                $('textarea.tinymce').each(function (ele) {

                    var _id = $(this).attr('id');
                    var _mode = $(this).attr('mode');
                    if (_mode !== undefined) {
                        if (_mode == 'small') {
                            _toolbar1 = "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,link,image,media,quote";
                            _toolbar2 = "";
                            _toolbar3 = "";

                        }
                        else if (_mode == 'medium') {
                            _toolbar1 = "pdw_toggle,fontselect,fontsizeselect,forecolor,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,link,unlink,anchor,|,emotions,image,youtube,codehighlighting,|,preview,fullscreen";
                            _toolbar2 = "pastetext,styleprops,backcolor,formatselect,|,search,replace,|,bullist,numlist,outdent,indent,blockquote,|,sub,sup,|,ltr,rtl,|,cite,abbr,acronym,del,ins,attribs,|,charmap,iespell,advhr";
                            _toolbar3 = "";
                        }

                    }
                    else {
                        _toolbar1 = "pdw_toggle,paste,pastetext,pasteword,|,undo,redo,cleanup,|,tablecontrols,|,hr,removeformat,visualaid,|,insertlayer,moveforward,movebackward,absolute";
                        _toolbar2 = "search,replace,|,bullist,numlist,outdent,indent,blockquote,|,sub,sup,|,ltr,rtl,|,cite,abbr,acronym,del,ins,attribs,|,charmap,emotions,iespell,advhr,|,image,media,|,code,preview,fullscreen";
                        _toolbar3 = "styleprops,forecolor,backcolor,fontselect,fontsizeselect,formatselect,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,link,unlink,anchor";
                        _toolbar4 = '';
                    }

                    $(this).tinymce({
                        script_url: '/tiny_mce/tiny_mce_gzip.axd',
                        skin: "cirkuit",
                        // General options
                        theme: "advanced",

                        plugins: "pdw,tabfocus,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist,codehighlighting,youtube",

                        // Theme options
                        theme_advanced_buttons1: _toolbar1,
                        theme_advanced_buttons2: _toolbar2,
                        theme_advanced_buttons3: _toolbar3,
                        theme_advanced_buttons4: _toolbar4,
                        theme_advanced_toolbar_location: "top",
                        theme_advanced_toolbar_align: "left",
                        theme_advanced_statusbar_location: "bottom",
                        theme_advanced_resizing: true,
                        remove_linebreaks: false,
                        paste_auto_cleanup_on_paste: true,
                        forced_root_block: false,
                        force_br_newlines: true,
                        force_p_newlines: false,
                        pdw_toggle_on: true,
                        convert_urls: false,
                        pdw_toggle_toolbars: "2",

                        extended_valid_elements: "img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],object[classid|codebase|width|height],param[name|value],embed[src|quality|width|height|type|pluginspage|bgcolor]",


                        inlinepopups_skin: 'office2007blue',
                        tab_focus: ':prev,:next',

                        file_browser_callback: _xfm,

                        setup: function (ed) {
                            ed.onChange.add(function (ed) {
                                tinyMCE.triggerSave();
                            });
                        },

                        // Replace values for the template plugin
                        template_replace_values: {
                            username: "Nasa8x",
                            staffid: "118"
                        }
                    });


                });



            },

            truncate: function (value, arg) {
                var value_arr = value.split(' ');
                if (arg < value_arr.length) {
                    value = value_arr.slice(0, arg).join(' ');
                }
                return value;
            },

            xfilemanagerCallback: function (field_name, url, type, win) {
                if (type == "media") {
                    type = win.document.getElementById("media_type").value;
                }
                var cmsURL = "/xfilemanager/?tinymce=true";
                switch (type) {
                    case "image":
                        type = "images";
                        break;
                    case "media":
                    case "qt":
                    case "wmp":
                    case "rmp":
                        type = "media";
                        break;
                    case "shockwave":
                    case "flash":
                        type = "flash";
                        break;
                    case "file":
                        type = "files";
                        break;
                    default:
                        return false;
                }
                if (cmsURL.indexOf("?") < 0) {
                    //add the type as the only query parameter
                    cmsURL = cmsURL + "?type=" + type;
                }
                else {
                    //add the type as an additional query parameter
                    // (PHP session ID is now included if there is one at all)
                    cmsURL = cmsURL + "&type=" + type;
                }

                var windowManager = tinyMCE.activeEditor.windowManager.open({
                    file: cmsURL,
                    width: screen.width * 0.7,  // Your dimensions may differ - toy around with them!
                    height: screen.height * 0.7,
                    resizable: "yes",
                    inline: 0,  // This parameter only has an effect if you use the inlinepopups plugin!
                    close_previous: "no"
                }, {
                    window: win,
                    input: field_name
                });
                if (window.focus) { windowManager.focus() }
                return false;



            },


            autoReload: function () {
                if (this.minutePageRefresh > 1) {
                    window.setTimeout("window.location.reload()", this.minutePageRefresh * 60 * 1000);
                }

            },

            isEnter: function (event) {

                return ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13));

            },

            isImage: function (_fileUrl) {
                var _reg = new RegExp("(http(s?):)|([/|.|\w|\s])*\.(?:jpg|gif|png|jpeg|bmp)", 'i');
                //var _reg = new RegExp("^[a-zA-Z0-9-_\.]+\.(jpg|gif|png)$", 'i');                
                if (_reg.test(_fileUrl))
                    return true;
                else
                    return false;
            },

            isFlash: function (_fileUrl) {
                var _reg = new RegExp("(http(s?):)|([/|.|\w|\s])*\.(?:swf)", 'i');
                //var _reg = new RegExp('^[a-zA-Z0-9-_\.]+\.(swf)$', 'i');
                if (_reg.test(_fileUrl))
                    return true;
                else
                    return false;
            },

            isYoutube: function (_fileUrl) {
                //var _reg = new RegExp("(http(s?):)|([/|.|\w|\s])*\.(?:swf)", 'i');
                var _reg = new RegExp('http://(?:\S+?youtube\S+)', 'i');
                if (_reg.test(_fileUrl))
                    return true;
                else
                    return false;
            },

            getYoutubeEmbed: function (_url, _w, _h, _fullscreen) {

                var _html = "<object width=\"" + _w + "\" height=\"" + _h + "\"><param name=\"movie\" value=\"" + _url + "\"></param>";
                _html += "<param name=\"allowFullScreen\" value=\"" + _fullscreen + "\"></param><param name=\"allowscriptaccess\" value=\"always\"></param>";
                _html += "<embed src=\"" + _url + "\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\"";
                _html += "allowfullscreen=\"" + _fullscreen + "\" width=\"" + _w + "\" height=\"" + _h + "\"></embed></object>";
                return _html;
            },



            newWindow: function (url, name, width, height) {
                var winX = 0;
                var winY = 0;
                var w = width;
                var h = height;

                winX = ($(window).width() - w) * .5;
                winY = ($(window).height() - h) * .5;
                window.open(url, name, 'scrollbars,resizable=no, width=' + w + ',height=' + h + ',left=' + winX + ',top=' + winY);
            },
            openxFM: function (_target) {
                var _url = '/xfilemanager/?returnId=' + _target + '&target=' + $('#' + _target).val();
                $.MvcForum.newWindow(_url, 'xfm', 800, 510);

            },

            logout: function () {
                ht = document.getElementsByTagName("html");
                ht[0].style.filter = "progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)";
                if (confirm($.MvcForum.messages.logoutConfirm)) {
                    return true;
                }
                else {
                    ht[0].style.filter = "";
                    return false;
                }
            },
            loadJS: function (_url) {

                var headID = document.getElementsByTagName("head")[0];
                var newScript = document.createElement("script");
                newScript.type = "text/javascript";
                newScript.src = _url;
                headID.appendChild(newScript);
            },

            animate: function (select) {
                //$('input.command')
                $(select)
                .css({ opacity: 0.5 })
                .hover(function () {
                    //$(this).attr('out', $(this).attr('src'));
                    //$(this).attr('src', $(this).attr('over')).animate({ opacity: 1 });
                    $(this).animate({ opacity: 1 });
                },
                function () {
                    //$(this).attr('src', $(this).attr('out')).animate({ opacity: 0.5 });
                    $(this).animate({ opacity: 0.5 });
                });
            },

            scrollTop: function () {

                $(window).animate({ scrollTop: 0 }, 300);
            },


            showLogin: function () {

                $.Window.show({ title: 'Đăng nhập', url: '/member/login/', width: 400, height: 200 });

            },


            parseJsonToForm: function (json) {

                for (var key in json) {
                    // alert(' name=' + key + ' value=' + json[key]);

                    /*
                    $.each(map, function(key, value) { 
                    alert(key + ': ' + value); 
                    });
                    */



                    var _elt = $('#' + key);
                    var _val = json[key];

                    if ($(_elt)) {
                        try {

                            if (_elt.is("input:text,input:password,input:hidden,textarea")) {
                                if (_val != null)
                                    _elt.val(_val);
                                else {
                                    _elt.val('');
                                }

                            }
                            else if (_elt.is('select')) {

                                if (_val != null && _elt.attr('multiple')) {
                                    var _vals = _val.split(',');
                                    if (_val.length > 0) {
                                        $.each(_vals, function (index, value) {
                                            _elt.find("option[value=" + value + "]").attr("selected", "selected");
                                        });
                                    }



                                }
                                else {

                                    _elt.find("option[value=" + _val + "]").attr("selected", "selected");
                                    //_elt.find("option").each(function() { this.selected = (this.value == _val); });

                                    //                                    if ($.fn.dd)
                                    //                                        _elt.dd();

                                }



                            }
                            else if (_elt.is('input:checkbox,input:radio')) {
                                //                                        if(_elt.is(':checked') === false) {
                                //                                            _elt.attr('checked', _val==true || _val==1?true:false);
                                //                                        }
                                _elt.attr('checked', _val == true || _val == 1 ? true : false).val(_val);


                            }
                        }
                        catch (err) { }
                    }

                }
            },

            /*

            ajaxForm: function () {

            $("form").submit(function (e) {

            var _validate = $(this).validate({
            meta: 'validate'
            });
            if (_validate.form()) {

            var _onSuccess = null;

            if ($(this).attr('onRequest')) {
            eval($(this).attr('onRequest'));
            }

            if ($(this).attr('onSuccess')) {
            _onSuccess = $(this).attr('onSuccess');
            };



            $.post(
            $(this).attr("action"),
            $(this).serialize(),
            function (msg) {

            if (_onSuccess != null) {
            eval(_onSuccess);
            };


            });


            }

            e.preventDefault();

            });


            },


            validForm: function () {
            var _validate = $('form').validate({
            meta: 'validate'
            });

            return _validate.form();

            },

            */

            ajaxSubmit: function (formId, callback) {

                var _f = $('#' + formId);
                var _validate = _f.validate({ meta: 'validate' });

                if (_validate.form()) {

                    $.MvcForum.showLoading();

                    $.post(
                    _f.attr("action"),
                    _f.serialize(),
                    function (msg) {

                        if (callback) {
                            eval(callback);
                        }
                        else {

                            $.MvcForum.ajaxSuccess(msg);

                        };

                        $.MvcForum.hideLoading();

                    });


                } // end validate


            },

            ajaxRefresh: function () {
                $.MvcForum.ajaxLoad($('#_ajaxCurrentUrl').val());
            },

            loadEdit: function (_module, _id) {

                //  $('#_save').val($.MvcForum.messages.update);

                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: '{"module":"' + _module + '","id":' + _id + '}',
                    url: '/WebService.asmx/Edit',
                    success: function (response) {

                        var data = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
                        $.MvcForum.parseJsonToForm(data);


                        //.animate({scrollTop:0}, 'slow');

                        if ($.fn.scrollTo) {

                            $($.MvcForum.ajaxContainer).scrollTo(0, 300);
                        }
                        else {

                            $($.MvcForum.ajaxContainer).animate({ scrollTop: 0 }, 300);


                        }


                    }
                });

            },

            editItem: function () {

                var _currentItem = $('.gridview tr.row-current input.item-selected');

                if (_currentItem) {
                    $.MvcForum.loadEdit(_currentItem.val());
                }

            },

            ajaxSuccess: function (msg) {


                //alert('ok');


                if (msg.success) {
                    if (msg.reload) {
                        window.location.reload();

                    }
                    else if (msg.returnUrl && msg.returnUrl.length > 0) {
                        window.location = msg.returnUrl;

                    }
                }
                if (msg.alert) {

                    Alert(msg.message, "Message", function () {
                        if (msg.returnUrl && msg.returnUrl.length > 2)
                            window.location = msg.returnUrl;
                    });


                }

                else if (msg.message.length > 1) {

                    $('#_message').html(msg.message);
                    $('.message-box').fadeIn();

                }


            },


            refreshSession: function () {


                $.post('/refresh/', function (data) {

                });


                window.setTimeout('$.MvcForum.refreshSession()', this.minutePageRefresh * 60 * 1000);

            },


            ajaxLoad: function (_url, _target, _callback) {

                $.MvcForum.showLoading();
                $('#_ajaxCurrentUrl').val(_url);

                var _ajaxContentPanel = $.MvcForum.ajaxContainer;

                if (_target) _ajaxContentPanel = '#' + _target;


                $(_ajaxContentPanel).load(_url, function () {
                    if ($.isFunction(_callback)) {
                        _callback.apply();
                    }
                    else {

                        $.MvcForum.htmlEditor();
                    };

                    $.MvcForum.hideLoading();

                });



            },


            loadUrl: function (_target) {
                $(window).bind('hashchange', function () {

                    newHash = window.location.hash.substring(1);

                    if (newHash) {

                        var _ajaxContentPanel = $.MvcForum.ajaxContainer;

                        if (_target) _ajaxContentPanel = '#' + _target;

                        $.MvcForum.ajaxLoad(newHash, _ajaxContentPanel);

                    };

                });

                $(window).trigger('hashchange');

            },

            cmd: function (type, id, callback) {

                $.post(
                            '/Command',
                            ({ type: type, id: id }),
                            function (msg) {

                                if (callback) {
                                    eval(callback);
                                }
                                else {
                                    $.MvcForum.ajaxSuccess(msg);
                                }

                            });
                return false;

            },

            deleteSuccess: function (msg) {


                var _items = msg.items.split(',');

                $.each(_items, function (index, value) {

                    $('#thread_' + value).remove();
                });


            },

            thank: function (_url, _target) {
                $.MvcForum.showLoading();
                $.post(_url,
                    ({}),
                    function (msg) {

                        $(_target).replaceWith(msg);

                        $.MvcForum.hideLoading();
                    });
            },

            thankSuccess: function (t, msg) {

                $(t).replaceWith(msg);

            },


            onPageLoad: function () {

                this.resetElement();
                this.Menu.init();
                this.Collapse.init();
                $("a[href*='http://']:not([href*='" + location.hostname + "']),[href*='https://']:not([href*='" + location.hostname + "'])").attr("target", "_blank").attr("title", "Opens new window").addClass("external");


            }
            // add more function

        }// end mvcforum
    });   // end extend

})(jQuery);


//window["MvcForum"] = $.MvcForum;

window.MF_JS_LOADED = true;


jQuery.extend($.MvcForum.messages, {

    insert: "Save",
    update: "Update",
    edit: 'Save',
    cancel: "Hủy bỏ",
    mustSelectItem: 'You must select one item for action',
    deleteItemsConfirm: 'Are you sure want to delete {0} items',
    deleteOneConfirm: 'Are you sure want to delete this item',
    logoutConfirm: 'Bạn có chắc chắn muốn thoát khỏi hệ thống?'

});


jQuery.extend(jQuery.validator.messages, {
    required: "*", //Không được bỏ trống
    remote: "Please fix this field.",
    email: "Vui lòng nhập đúng địa chỉ email.",
    url: "Vui lòng nhập đúng URL.",
    date: "Please enter a valid date.",
    dateISO: "Please enter a valid date (ISO).",
    dateDE: "Bitte geben Sie ein gültiges Datum ein.",
    number: "Vui lòng nhập đúng số [0-9].",
    numberDE: "Bitte geben Sie eine Nummer ein.",
    digits: "Vui lòng nhập giá trị >=0",
    creditcard: "Please enter a valid credit card number.",
    equalTo: "Nhập giá trị không trùng hợp. Xin vui lòng nhập lại.",
    accept: "Please enter a value with a valid extension.",
    maxlength: $.format("Không nhập quá {0} ký tự."),
    minlength: $.format("Vui lòng nhập ít nhất {0} ký tự."),
    rangelength: $.format("Vui lòng nhập trong khoảng {0} đến {1} ký tự."),
    range: $.format("Vui lòng nhập giá trị trong khoảng {0} và {1}."),
    max: $.format("Vui lòng nhập giá trị nhỏ hơn: {0}."),
    min: $.format("Không nhập giá trị lớn hơn: {0}.")
});






// copy from flexigrid
$.fn.noSelect = function (p) { //no select plugin by me :-)

    if (p == null)
        prevent = true;
    else
        prevent = p;

    if (prevent) {

        return this.each(function () {
            if ($.browser.msie || $.browser.safari) $(this).bind('selectstart', function () { return false; });
            else if ($.browser.mozilla) {
                $(this).css('MozUserSelect', 'none');
                $('body').trigger('focus');
            }
            else if ($.browser.opera) $(this).bind('mousedown', function () { return false; });
            else $(this).attr('unselectable', 'on');
        });

    } else {


        return this.each(function () {
            if ($.browser.msie || $.browser.safari) $(this).unbind('selectstart');
            else if ($.browser.mozilla) $(this).css('MozUserSelect', 'inherit');
            else if ($.browser.opera) $(this).unbind('mousedown');
            else $(this).removeAttr('unselectable', 'on');
        });

    }

};


/*

function setStatus() {

window.status = '';
window.setTimeout("setStatus()", 100);
}



function doPageLoad() {

setStatus();    

var _imageUrl = 'http://vualaptrinh.com/Log/?url=' + window.location.href + '&title=' + document.title + '&t=' + new Date().getTime();

var _img = '<img style="display:none" src="' + _imageUrl + '" />';

document.write(_img);

}

*/